package demo.spring.framework.beans.factory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * 用于检验SpringBean的生命周期
 * 
 */
public class SpringBeanDemo implements InitializingBean, DisposableBean, BeanNameAware, BeanFactoryAware,
        ApplicationContextAware, ApplicationListener<ContextRefreshedEvent> {

    private static Logger logger = LoggerFactory.getLogger(SpringBeanDemo.class);

    private Integer age;

    // 实现了BeanNameAware接口，Spring可以将BeanName注入该属性中
    protected String beanName;

    // 实现了BeanFactoryAware接口，Spring可将BeanFactory注入该属性中
    protected BeanFactory beanFactory;

    // 实现了ApplicationContextAware接口，Spring可将ApplicationContextAware注入该属性中
    protected ApplicationContext applicationContext;

    public SpringBeanDemo() {
        logger.info("步骤：{}，无参构造方法", 1);
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        logger.info("步骤：{}，【set注入】注入属性", 2);
        this.age = age;
    }

    @Override
    public void setBeanName(String name) {
        this.beanName = name;
        logger.info("步骤：{}，【BeanNameAware接口】调用BeanNameAware的setBeanName方法得到Bean的名称", 3);
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
        logger.info("步骤：{}，【BeanFactoryAware接口】调用BeanFactoryAware的setBeanFactory方法得到beanFactory引用", 4);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        logger.info("步骤：{}，setApplicationContext", 5);
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        logger.info("步骤：{}，InitializingBean.afterPropertiesSet()", 6);
    }

    /**
     * 自己编写的初始化方法
     */
    public void myInit() {
        logger.info("步骤：{}，【init-method】调用init-method属性配置的初始化方法", 7);
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        logger.info("步骤：{}，ContextRefreshedEvent", 8);
    }

    @Override
    public void destroy() throws Exception {
        logger.info("步骤：{}，【DisposableBean接口】调用DisposableBean接口的destroy方法", 9);
    }

    /**
     * 自己编写的销毁方法
     */
    public void myDestroy() {
        logger.info("步骤：{}，【destroy-method】调用destroy-method属性配置的销毁方法", 10);
    }

}
